<?php
namespace addons\facrm\controller\facrm\contract;


use addons\facrm\library\BackendApi;
use fast\Random;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;


/**
 * 合同管理
 */
class Index extends BackendApi
{

    protected $model = null;
    /**
     * 快速搜索时执行查找的字段
     */
    protected $searchFields = 'name,number';
    protected $childrenAdminIds = [];
    protected $noNeedRight = ['selectpage','payurl'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('\app\admin\model\facrm\Contract');
        $this->request->filter(['strip_tags']);
    }

    /**
     * 合同列表
     * @ApiParams(name="customer_id", type="int", required=false, description="客户id")
     * @ApiParams(name="expire_handle", type="int", required=false, description="如果是100就查询回款的合同")
     * @ApiBody ("其它参数参考电脑版")
     */
    public function index($scene_list = array())
    {
        $scene_list = $scene_list ? $scene_list : ['all' => __('全部合同')];
        $filter_w = $this->getFilterWhere($scene_list);

        $customer_id = $this->request->request("customer_id");
        if ($customer_id) {
            $filter_w['customer_id'] = $customer_id;
        }
        $filter = $this->request->get("filter", '');
        $filter = (array)json_decode($filter, true);
        if (isset($filter['expire_handle'])) {
            if ($filter['expire_handle']==100){//如果是查询需要回款的合同
                $filter_w['money'] = ['exp',Db::raw(' > return_money')];
                unset($filter['expire_handle']);
            }
            $this->request->get(['filter' => json_encode($filter)]);
        }


        //如果发送的来源是Selectpage，则转发到Selectpage
        if ($this->request->request('keyField')) {
            $this->request->request(['custom' => $filter_w]);
            return parent::selectpage();
        }

        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->where($filter_w)
            ->with([
                'createUser' => function ($user) {
                    $user->field('id,username,nickname');
                },
                'orderAdmin' => function ($user) {
                    $user->field('id,username,nickname');
                },
                'customer' => function ($customer) {
                    $customer->field('id,name');
                },
            ])
            ->order($sort, $order)
            ->limit($offset, $limit)->fetchSql(false)
            ->select();
        $result = array("rows" => $list);

        return $this->success('', $result);
    }
    /**
     * 我的下属/合同
     */
    public function lists()
    {
        $scene_list=[];
        //判断是否有全部合同权限
        if (!$this->auth->check("facrm/contract/index/index")){
            $scene_list=['our' => '我们的合同','owner' => '我的合同', 'branch' => '下属合同'];
        }
        return $this->index($scene_list);
    }

    /**
     * 合同添加
     * @ApiMethod (POST|get)
     * @ApiParams(name="customer_id", type="int", required=true, description="客户id")
     * @ApiParams(name="number", type="string", required=true, description="合同编码")
     * @ApiParams(name="name", type="string", required=true, description="合同名称")
     * @ApiParams(name="business_id", type="int", required=false, description="商机id,最好填写")
     * @ApiParams(name="money", type="int", required=true, description="合同金额")
     * @ApiParams(name="order_time", type="string", required=true, description="下单时间")
     * @ApiParams(name="start_time", type="string", required=true, description="合同开始时间")
     * @ApiParams(name="end_time", type="string", required=true, description="合同结束时间")
     * @ApiParams(name="contacts_id", type="int", required=false, description="客户联系人id")
     * @ApiParams(name="order_admin_id", type="int", required=true, description="公司签约人id")
     * @ApiParams(name="flow_admin_id", type="int", required=true, description="审批人ID，多个逗号隔开")
     * @ApiParams(name="remark", type="string", required=true, description="备注")
     * @ApiParams(name="discount_rate", type="int", required=false, description="优惠率")
     * @ApiParams(name="total_price", type="int", required=false, description="商品金额")
     * @ApiParams(name="product[0][product_id]", type="int", required=false, description="商品id")
     * @ApiParams(name="product[0][nums]", type="int", required=false, description="数量")
     * @ApiParams(name="product[0][price]", type="int", required=false, description="商品单价")
     * @ApiParams(name="product[0][subtotal]", type="int", required=false, description="商品小计")
     * @ApiParams(name="product[0][remarks]", type="remark", required=false, description="备注")
     * @ApiBody ("get获取审批流程config为1是固定审批0是授权。flow_admin_id是固定审批时候的用户ID")
     */
    public function add()
    {
        $flow = model('\app\admin\model\facrm\Flow');
        $flow_r = $flow->where('types', 'contract')->where("status", 1)->order('id desc')->find();
        if (!$flow_r) $this->error(__('审批配置不存在，请先配置'));

        if ($this->request->isPost()) {
            $params = $this->request->post();
            if (!isset($params['customer_id']))
                $this->error(__('请选择客户'));

            $customer = model('\app\admin\model\facrm\Customer');
            $row_c = $customer->get($params['customer_id']);

            if (!$row_c)
                $this->error(__('没有找到客户'));

            $params['order_time'] = isset($params['order_time']) && $params['order_time'] ? strtotime($params['order_time']) : 0;
            $params['start_time'] = isset($params['start_time']) && $params['start_time'] ? strtotime($params['start_time']) : 0;
            $params['end_time'] = isset($params['end_time']) && $params['end_time'] ? strtotime($params['end_time']) : 0;
            $params = array_merge($params, [
                'create_user_id' => $this->auth->id,
                'owner_user_id' => $this->auth->id,
                'type_id' => '1',
                'check_status' => 0,
            ]);
            $this->excludeFields=['product'];
            $params = $this->preExcludeFields($params);

            $result = false;
            $contract_id = 0;
            Db::startTrans();
            try {

                $product_data = ($this->request->post("product/a"));
                $result = $this->model->add($params,$product_data);
                $contract_id = $this->model->id;

                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                //处理合同审核流程
                $flow->addFlow($contract_id, $this->auth->id, 'contract', $flow_r);
                hook("facrm_contract_add", array_merge($params, ['id' => $contract_id]));
                $this->success();
            } else {
                $this->error(__('No rows were inserted'));
            }
        }
        if ($flow_r->config==1)//如果固定审批
            $flow_r['flow_admin_id']=$flow->getAdminIds($flow_r,$this->auth->id);

        $this->success('',$flow_r);
    }

    /**
     * 我的下属/合同[添加]
     * @param null $param 和add参数意义
     */
    public function contractadd(){

        $flow = model('\app\admin\model\facrm\Flow');
        $flow_r = $flow->where('types', 'contract')->where("status", 1)->order('id desc')->find();
        if (!$flow_r) $this->error(__('审批配置不存在，请先配置'));

        if ($this->request->isPost()) {
            $params = $this->request->post();

            if (!isset($params['customer_id']))
                $this->error(__('请选择客户'));

            $customer = model('\app\admin\model\facrm\Customer');
            $row_c = $customer->get($params['customer_id']);


            if (!$row_c)
                $this->error(__('没有找到客户'));

            if (!isset($params['customer_id']))
                $this->error(__('请选择客户'));

            if (!$row_c)
                $this->error(__('没有找到客户'));

            //检查是否有权限
            $Auth = new  \addons\facrm\library\Auth();
            if (!$Auth->checkCustomerAuth($row_c, $this->auth)) {
                $this->error(__("您没有权限"));
            }
            $this->add();
        }
        if ($flow_r->config==1)//如果固定审批
            $flow_r['flow_admin_id']=$flow->getAdminIds($flow_r,$this->auth->id);

        $this->success('',$flow_r);


    }

    /**
     * 合同修改
     * @ApiMethod (POST|GET)
     * @ApiParams(name="id", type="int", required=true, description="合同ID")
     * @ApiBody ("get是获取信息,要修改的字段提交过来，参考添加，审核通过的只能修改负责人和备注、处理情况")
     */
    public function edit()
    {
        $id = $this->request->request('id', '', 'intval');
        if (!$id) {
            $this->error(__('No Results were found'));
        }
        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $flow = model('\app\admin\model\facrm\Flow');
        if ($row->flow_id){
            $flow->where('id',$row->flow_id);//处理流程被删除
        }
        $flow_r = $flow->where('types', 'contract')->where("status",1)->order('id desc')->find();
        if ($this->request->isPost()) {

            $params = $this->request->post();
            if ($params) {
                if ($row->check_status==2) {
                    //审核通过的只能修改负责人和备注、处理情况、续费单价
                    $params_update =array();
                    isset($params['remark'])?$params_update['remark']=$params['remark']:'';
                    isset($params['owner_user_id'])?$params_update['owner_user_id']=$params['owner_user_id']:'';
                    isset($params['expire_handle'])?$params_update['expire_handle']=$params['expire_handle']:'';
                    isset($params['renewmoeny'])?$params_update['renewmoeny']=$params['renewmoeny']:'';
                    $result = $row->allowField(true)->save($params_update);
                    return $this->success();
                }elseif($row->check_status==1){
                    //审核中的不能修改
                    return $this->error(__("审核中的不能修改，请先驳回再修改"));
                }


                $params['order_time'] = isset($params['order_time'])&&$params['order_time'] ? strtotime($params['order_time']) : 0;
                $params['start_time'] = isset($params['start_time'])&&$params['start_time'] ? strtotime($params['start_time']) : 0;
                $params['end_time'] = isset($params['end_time'])&&$params['end_time'] ? strtotime($params['end_time']) : 0;
                $params['check_status'] = 0;//重新把合同改成待审核状态


                $this->excludeFields=['product'];
                $params = $this->preExcludeFields($params);
                $result = false;
                $contract_id = $row->id;
                Db::startTrans();
                try {
                    $product_data = ($this->request->post("product/a"));
                    $result = $this->model->edit($row, $params, $product_data);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    //处理合同审核流程
                    $flow->addFlow($contract_id,$this->auth->id,'contract',$flow_r);
                    hook("facrm_contract_edit", array_merge($params, ['id' => $contract_id]));
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $row->product;
        return $this->success('', ['row'=>$row,'flow'=>$flow_r]);

    }

    /**
     * 合同删除
     * @ApiMethod (POST)
     * @ApiParams(name="ids", type="int", required=true, description="合同ids,多个用逗号隔开")
     */
    public function del()
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
            $list = $this->model->where($pk, 'in', $ids)->where('owner_user_id', 'in', $this->childrenAdminIds)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }


    /**
     * 选择合同
     * @return \think\response\Json
     */
    public function selectpage()
    {
        $this->request->request(['showField' => 'name']);
        $this->request->request(['keyField' => 'id']);
        $this->request->request(['searchField' => array('name|id')]);
        $this->selectpageFields =['id','concat(name,"(",id,")") as name','customer_id'];
        //判断是否有全部合同权限、没有就获取自己的
        if ($this->auth->check("facrm/contract/index/index")){
            return parent::selectpage();
        }else{
            return $this->index(['owner' => '我的合同', 'branch' => '下属合同']);
        }

    }


    /**
     * 生成续费链接
     * @param null $ids 合同id
     * @return string
     * @throws Exception
     */
    public function payurl($ids = null)
    {
        $ids = $this->request->request('ids', '', 'intval');
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $check_data=\addons\facrm\library\Order::checkPay($row, 'renew',$pay_config);
        if ($check_data['code']!=1){
            $this->error(__($check_data['msg']));
        }
        //10天就重新刷新支付凭证
        if (!$row->renewtoken||(time()-$row->update_time)>864000){
            $row->renewtoken = md5($row->id . uniqid() . Random::uuid());
            $row->save();
        }


        $url = addon_url('facrm/order/renew', ['pay_token' => $row->renewtoken], '', true);
        $this->success('',['url'=>$url,'qrcode_url'=>addon_url('facrm/order/qrcode',[],false,true)."?text={$url}",'row'=>$row]);

    }


    /**
     * 处理过滤where条件
     * @return array
     */
    private function getFilterWhere($scene_list)
    {

        $filter = $this->request->get("filter", '');
        $filter = (array)json_decode($filter, true);
        $filter_w = [];
        //也可以用array_key_first 要求php7.3
        $filter['scene_id'] = isset($filter['scene_id']) ? $filter['scene_id'] : (array_keys($scene_list)[0]);
        if (isset($filter['scene_id'])) {
            if (!isset($scene_list[$filter['scene_id']])) {
                $this->error(__("您没有权限:scene"));
            }
            switch ($filter['scene_id']) {
                case 'all':
                    //全部
                    break;
                case 'owner':
                    //我的
                    $filter_w['order_admin_id'] = $this->auth->id;
                    break;
                case 'branch':
                    //下级
                    $this->childrenAdminIds = $this->auth->getChildrenAdminIds(false);
                    $filter_w['order_admin_id'] = ['in', $this->childrenAdminIds];
                    break;
                case 'our':
                    //下属和自己
                    $this->childrenAdminIds = $this->auth->getChildrenAdminIds(true);
                    $filter_w['order_admin_id'] = ['in', $this->childrenAdminIds];
                    break;
                default://
                    $filter_w['order_admin_id'] = $this->auth->id;
            }
            unset($filter['scene_id']);
            $this->request->get(['filter' => json_encode($filter)]);
        }
        return $filter_w;
    }

}
